/*****************************************************************************************
**  Author:jxx 2022
**  QQ:283591387
**完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
**常用示例见：http://v2.volcore.xyz/document/vueDev
**后台操作见：http://v2.volcore.xyz/document/netCoreDev
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
// import modelHeader from "../goodsin_class/goodsInCom.vue"
import modelHeader from "../goods_inventory_warehouse_xm/goodsInventoryWarehouse_xm.vue"
import gridHeader from "@/components/print/selectTemplet.vue"
import { ElMessage, ElMessageBox } from 'element-plus'

let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: '',
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    async onInit() {
      this.queryFields=['WHSE_name_out','CreateDate']
      this.textInline = false
      this.detailOptions.textInline = false
      let startTime = await this.base.getOneWeekAgoDate()
      let endTime = await this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]
      // this.setFiexdSearchForm(true);
      // this.columns.forEach(column => {
      //   if (column.field == 'Goods_num') {
      //     column.click = (row, column, event) => {
      //       this.$message.info(JSON.stringify(row.Goods_num));
      //     };
      //   }
      // })
      //获取当前用户信息
      // let url = "api/q_goodsOut_class/getUserInfo"
      // this.http.post(url, {}, "").then(reslut => {
      //   try {
      //     this.user_Id = reslut.user_Id
      //   } catch (error) {
      //     console.error(error)
      //   }
      // })
      this.UpdateState = false //自定义用户编辑权限
      if (this.filterPermission("q_warehouse_allot", 'Update')) {
        this.UpdateState = true
      }
      if (this.$route.path == "/q_warehouse_allot" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Coding = null
        // this.searchFormFields.Goods_num = null
        // this.searchFormFields.WHSE_name_out = null
        // this.searchFormFields.WHSE_name_in = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['Coding','Goods_num',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (!selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      // this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })
      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      this.detailOptions.buttons.unshift({
        name: "选择商品",//按钮名称
        icon: 'el-icon-plus',//按钮图标，参照iview图标
        type: 'primary',
        plain: true,
        onClick: function () { //触发事件
          if (this.rowschild&&this.$refs.detail.rowData.length) {
            this.rowschild.click()
          }
          // const WHSE_name_out_val = JSON.stringify(this.editFormFields.WHSE_name_out)
          // if (WHSE_name_out_val == "[]" || WHSE_name_out_val == "null") {
            if (!this.editFormFields.WHSE_name_out) {
            this.base.ElMessageFn('请选择调出机构')
            return;
          }
          // const WHSE_name_in_val = JSON.stringify(this.editFormFields.WHSE_name_in)
          // if (WHSE_name_in_val == "[]" || WHSE_name_in_val == "null") {
            if (!this.editFormFields.WHSE_name_in) {
            this.base.ElMessageFn('请选择调入机构')
            return;
          }
          this.$store.commit("setTabelText", true)
          // this.$refs.modelHeader.open(this.editFormFields.WHSE_name_out[this.editFormFields.WHSE_name_out.length - 1])
          this.$refs.modelHeader.open(this.editFormFields.WHSE_name_out)

        }
      })
      this.detailOptions.columns.forEach(x => {
        if (x.field == 'WHSE_name_in') {
          x.filter = false
        }
      })
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == "Tax_rate") {
            x.onChange = (e) => {
              if (this.rowschild&&this.$refs.detail.rowData.length) {
                this.rowschild.click()
              }
            }
          }
        })
      })
      // //明细表点击表格时触发编辑方法
      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_warehouse_allot" || this.rowAuditStatus != 0) {//|| !this.CreateUserBoole
          return false
        }
        // const WHSE_name_in_val = JSON.stringify(this.editFormFields.WHSE_name_in)
        // if (WHSE_name_in_val == "[]" || WHSE_name_in_val == "null") {
          if (!this.editFormFields.WHSE_name_in) {
          this.base.ElMessageFn('请选择调入机构')
          return false;
        }
        /*
        if (this.currentAction != 'Add' && !this.statusOff) {
          return false
        }
        //------test 限制同一用户编辑
        if (this.currentAction == 'Add') {
          //可以继续
        } else if (this.currentAction == 'Update' && !this.statusOff || !this.user_id_boole) {
          return false
        }
        //------test 限制同一用户编辑---end*/
        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        this.rowschild = rows[0].childNodes[2]
        setTimeout(() => {
          // 调出数量
          let testInputDom = rows[index].querySelectorAll("td")[6].querySelector("input")
          if (testInputDom) {
            testInputDom.addEventListener("keyup", (e) => {
              if (+testInputDom.value) {
                // row.Total_price = e.target.value * row.CostPrice
                // const num = row.Tax_exclusive * e.target.value
                // row.Tax_exclusive_exWarehouse_total_price = this.roundToFourDecimals(num)
                if (row.AvailableQuantity < +e.target.value) {
                  ElMessage.closeAll()
                  ElMessage({
                    message: '调出数量大于可用数量',
                    type: 'warning',
                  })
                } else {
                  ElMessage.closeAll()
                }
                /*  if (row.WHSE_name_out) {
                    let url = `api/q_goods_inventory/getgoodsquantity?kw=${row.WHSE_name_out}&bm=${row.Goods_sub}`
                    this.http.post(url, {}, "").then(({ rows }) => {
                      try {
                        if (typeof rows[0] == "object") {
                          let data = rows[0]
                          if (+data.goods_inventory_quantity < + testInputDom.value) {
                            this.$message.error("此商品在该库位实际库存" + data.goods_inventory_quantity)
                            e.target.blur()
                            // 鼠标聚焦时无法清除内容
                            setTimeout(() => {
                              row.Goods_num = null
                              setTimeout(() => {
                                e.target.focus()
                              }, 0)
                            }, 0)
                          }
                        } else if (rows[0] == null) {
                          this.$message.error("此商品在该库位暂无库存")
                          e.target.blur()
                          setTimeout(() => {
                            row.Goods_num = null
                            setTimeout(() => {
                              e.target.focus()
                            }, 0)
                          }, 0)
                        }
                      } catch (error) {
                        console.log("错误", error);
                      }
  
                    })
                  }
                
                
                */
              } else {
                ElMessage.closeAll()
                ElMessage({
                  message: '请输入数字',
                  type: 'warning',
                })
                // row.Total_price = 0
                // row.Tax_exclusive_exWarehouse_total_price = 0
              }
            })
          }
        }, 0)

        this.detailOptions.columns.forEach(item => {
          if (item.field == "WHSE_name_in") {
            if (!row.Goods_sub) {
              return
            }
            // this.base.getWHSEName(item, row.Goods_sub, false, this.editFormFields.WHSE_name_in[this.editFormFields.WHSE_name_in.length - 1])
            this.base.getWHSEName(item, row.Goods_sub, false, this.editFormFields.WHSE_name_in)
          }
        })

        return true
      }

      //#region
      // this.detailOptions.columns.forEach(x => {
      //   if (x.field == 'WHSE_name_out') {
      //     x.onChange = (column, row, tableData) => {
      //       if (column.Goods_num) {
      //         let url = `api/q_goods_inventory/getgoodsquantity?kw=${column.WHSE_name_out}&bm=${column.Goods_sub}`
      //         this.http.post(url, {}, "").then(({ rows }) => {
      //           try {
      //             if (typeof rows[0] == "object") {
      //               let data = rows[0]
      //               if (+data.goods_inventory_quantity < + column.Goods_num) {
      //                 this.$message.error("此商品在该库位实际库存" + data.goods_inventory_quantity)
      //                 setTimeout(() => {
      //                   column.Goods_num = null
      //                 }, 0)
      //               }
      //             } else if (rows[0] == null) {
      //               this.$message.error("此商品在该库位暂无库存")
      //               column.Goods_num = null
      //             }
      //           } catch (error) {
      //             console.log("错误", error);
      //           }

      //         })
      //       }
      //     }
      //   }
      // })
      //#endregion
    },
    WHSE_IdDisableFn() {
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == 'WHSE_name_out' || x.field == 'WHSE_name_in') {
            x.disabled = true
          }
        })
      })
    },
   async searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path == "/q_warehouse_allot" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Allot_id",param)
        // const sectionState = ["[null,null]",JSON.stringify(["",null]),JSON.stringify([null,""]),JSON.stringify(["",""])]
        // const dateState=sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Coding||this.searchFormFields.Goods_num ||!dateState) {
        //    param.wheres=param.wheres.filter(item=>item.name!="Allot_id")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => { return x.AuditStatus == 1 });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
     
      return true;
    },
    async addBeforeAsync(formData) {
      // if (!this.$refs.detail.rowData.length) {
      //   this.base.ElMessageFn('明细表不可为空', "error")
      //   return false
      // }
      // let boole = formData.detailData.every(item => item.Goods_num > 0 && +item.Goods_num)
      // if (!boole) {
      //   this.base.ElMessageFn("明细表中数量请大于零")
      //   return false;
      // }
      return this.testAdd(formData)
    },
    async updateBeforeAsync(formData) {
      // if (!this.$refs.detail.rowData.length) {
      //   this.base.ElMessageFn('明细表不可为空', "error")
      //   return false
      // }
      // let boole = formData.detailData.every(item => item.Goods_num > 0 && +item.Goods_num)
      // if (!boole) {
      //   this.base.ElMessageFn("明细表中数量请大于零")
      //   return false;
      // }
      return this.testAdd(formData)
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row);
    },
    delDetailRow(rows) { //弹出框删除明细表的行数据(只是对table操作，并没有操作后台)
      try {
        if (rows.length == this.$refs.detail.rowData.length) {
          this.$store.commit("setWHSE_time", true)
          this.$store.commit("setWHSE_disabled", true)
          this.WHSE_Interval = setInterval(() => {
            console.log("WHSE_Interval", this.WHSE_Interval)
            this.editFormOptions.forEach(item => {
              item.forEach(x => {
                if (x.field == 'WHSE_name_out' || x.field == 'WHSE_name_in') {
                  if (this.$store.state.WHSE_disabled) {
                    x.disabled = true
                  } else {
                    x.disabled = false
                  }
                }
              })
            })
            if (!this.$store.state.WHSE_time) {
              clearInterval(this.WHSE_Interval)
              console.log("WHSE_Interval清除", this.WHSE_Interval)

            }
          }, 500)

        }
      } catch {
        console.log("删除catch",)
      }
      return true;
    },
    async detailRowClick({ row, column, event }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_warehouse_allot" || this.rowAuditStatus != 0) { return }//|| !this.CreateUserBoole
      // if (this.currentAction == 'Add' || this.statusOff && this.user_Id == row.CreateID) {
      // if (this.currentAction == 'Add' || this.statusOff) {
      let selectDate = null
      let nodeName = event.currentTarget.nodeName == "DIV"
      if (nodeName) {
        // setTimeout(() => {
        //   this.detailOptions.columns.forEach(item => {
        //     if (item.field == "WHSE_name_in") {
        //       selectDate = item.bind.data
        //     }
        //   })
        //   selectDate = this.getInSelectDate(row.Goods_sub, selectDate, row.WHSE_name_out)
        // }, 0)
      }
      if (column.property == "Goods_num" || column.property == "WHSE_name_in" || column.property == "Remark") {
        //#region
        // this.detailOptions.columns.forEach(item => {
        //   if (item.field == "WHSE_name_in") {
        //     selectDate = item.bind.data
        //     let currentTarget = event.currentTarget
        //     setTimeout(() => {
        //       let selectDom = currentTarget.querySelectorAll(".el-select")
        //       selectDom[0].addEventListener("click", () => {
        //         if (selectDate instanceof Array) {
        //           selectDate = this.getInSelectDate(row.Goods_sub, selectDate, row.WHSE_name_out)
        //         }
        //       })
        //     }, 0)
        //   }
        // })
        //#endregion

        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }

        // }
      }
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      // this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_warehouse_allot" || this.rowAuditStatus != 0) {//|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
      /*
       this.user_id_boole = this.user_Id == row.CreateID
       if (this.currentAction != 'Add') {
         if (this.boxButtons[0]) {
           this.boxButtons[0].hidden = true
         }
         this.editFormOptions.forEach(item => {
           item.forEach(x => {
             this.detailOptions.buttons.forEach(item => {
               item.hidden = true
             })
             if (x.field == "Remark") {
               x.disabled = true
             }
           })
         })
       }
       // 新建
       if (this.currentAction == 'Add') {
         this.getModuleStatus()
       } else if (this.currentAction == 'update' && this.UpdateState) {
         let url = "api/Sys_WorkFlow/getSteps?tableName=q_warehouse_allot"
         await this.http.post(url, [row.Allot_id], "").then(reslut => {
           try {
             this.statusOff = reslut.list[1].isCurrent
             if (this.statusOff && this.user_id_boole) {
               // if (this.statusOff) {
               this.getModuleStatus()
             }
           } catch (error) {
             console.log("错误", error);
           }
         })
       }
      */
    },
    modelOpenAfter(row) {
      this.rowschild = null
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == "Total_price" || x.field == "Tax_exclusive_exWarehouse_total_price") {
            x.hidden = true
          }
          if (x.field == "Remark" || x.field == "WHSE_name_out" || x.field == "WHSE_name_in") {
            x.disabled = false
          } else {
            x.disabled = true
          }
          if (this.currentAction != 'Add' && (x.field == "WHSE_name_out" || x.field == "WHSE_name_in")) {
            x.disabled = true
          }
          if (this.$route.path != "/q_warehouse_allot" || this.rowAuditStatus != 0) {//|| !this.CreateUserBoole
            x.disabled = true
          }
        })
      })
    },
    async getSummary(formData) {
      let detailRowData = this.$refs.detail.rowData
      let num = 0
      // let summaryPrc = 0
      // let summaryPrc2 = 0
      let summaryNum = 0
      await detailRowData.forEach(item => {
        // summaryPrc += item.Total_price
        // summaryPrc2 += item.Tax_exclusive_exWarehouse_total_price
        summaryNum += +item.Goods_num
        if (item.Goods_num && item.WHSE_name_out && item.WHSE_name_in) num++
      })
      // formData.mainData.Goods_num = summaryNum
      // formData.mainData.Total_price = summaryPrc
      // formData.mainData.Tax_exclusive_exWarehouse_total_price = summaryPrc2

      if (detailRowData.length == num) {
        return true
      } else {
        this.$message.error("请正确选择商品")
        return false
      }
    },
    async testAdd(formData) {
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      if (!this.editFormFields.WHSE_name_out) {
        this.base.ElMessageFn('请选择调出机构')
        return false
      }
      if (!this.editFormFields.WHSE_name_in) {
        this.base.ElMessageFn('请选择调入机构')
        return false
      }
      let boole11 = formData.detailData.every(item => item.WHSE_name_in)
      if (!boole11) {
        this.base.ElMessageFn("明细表中请选择调入库位")
        return false;
      }
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0 )
      if (boole2) {
        this.base.ElMessageFn("明细表中调出数量不可为零或空")
        return false;
      }
      let boole = formData.detailData.some(item => item.Goods_num == "" || item.Goods_num == null || item.Goods_num == undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写调出数量")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中调出数量请填写有效正数")
        return false;
      }
      let boole4 = formData.detailData.some(item => +item.Goods_num >+item.AvailableQuantity)
      if (boole4) {
        this.base.ElMessageFn("明细表中调出数量大于可用数量")
        return false;
      }
      return true
    },
    /*
    detailBeginEditFn() {
      this.detailOptions.beginEdit = (row, column, index) => {
        this.detailOptions.columns.forEach(item => {
          if (item.field == "WHSE_name_out") {
            let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row.Goods_sub}`
            item.bind.data.forEach((d) => {
              d.hidden = true;
            });
            this.http.post(selectUrl, {}, "").then(reslut => {
              item.bind.data.forEach(d => {
                d.hidden = true
              })
              item.bind.data.forEach(d => {
                reslut.rows.forEach(j => {
                  if (d.key == j.WHSE_no) {
                    d.hidden = false
                  }
                })
              })
              // row.WHSE_name = item.bind.data.filter(x => x.hidden == false)[0].key
            })
          }
        })
        return true
      }
    },*/
    // async getOutSelectDate(sub, selectDate) {
    //   selectDate.forEach(d => {
    //     d.hidden = true
    //   })
    //   //这里请求出库的下拉框数据，请求地址需要改变
    //   let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${sub} `
    //   await this.http.post(selectUrl, {}, "").then(reslut => {
    //     selectDate.forEach(d => {
    //       d.hidden = true
    //     })
    //     // selectDate.forEach(d => {
    //     //   reslut.rows.forEach(j => {
    //     //     if (d.key == j.WHSE_no) {
    //     //       d.hidden = false
    //     //     }
    //     //   })
    //     // })
    //     selectDate.forEach(d => {
    //       reslut.forEach(j => {
    //         if (d.key == j.WHSE_no) {
    //           d.hidden = false
    //         }
    //       })
    //     })
    //   })
    //   return selectDate
    // },
    // async getInSelectDate(sub, selectDate, WHSE_name_out) {
    //   selectDate.forEach(d => {
    //     d.hidden = true
    //   })
    //   let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${sub} `
    //   await this.http.post(selectUrl, {}, "").then(reslut => {
    //     selectDate.forEach(d => {
    //       d.hidden = true
    //     })
    //     selectDate.forEach(d => {
    //       // reslut.rows.forEach(j => {
    //       //   if (d.key == j.WHSE_no && d.key != WHSE_name_out) {
    //       //     d.hidden = false
    //       //   }
    //       // })
    //       reslut.forEach(j => {
    //         if (d.key == j.WHSE_no && d.key != WHSE_name_out) {
    //           d.hidden = false
    //         }
    //       })
    //     })
    //   })
    //   return selectDate
    // },
    // async getModuleStatus() {
    //   this.boxButtons[0].hidden = false
    //   this.editFormOptions.forEach(item => {
    //     item.forEach(x => {
    //       this.detailOptions.buttons.forEach(i => {
    //         i.hidden = false
    //       })
    //       x.disabled = true
    //       if (x.field == "Remark") {
    //         x.disabled = false
    //       }
    //     })
    //   })
    // },
    // roundToFourDecimals(number) {
    //   return Math.round(number * 10000) / 10000;
    // }
  }
};
export default extension;
